package com.ssyc.student.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.ssyc.common.base.BaseActivity;
import com.ssyc.common.base.BaseApplication;
import com.ssyc.common.bean.BusInfo;
import com.ssyc.common.http.HttpAdress;
import com.ssyc.common.http.HttpUtils;
import com.ssyc.common.manager.AccountUtils;
import com.ssyc.common.manager.MediaPlayerManager;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.MathUtil;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.common.view.ZzHorizontalProgressBar;
import com.ssyc.common.view.dialog.CustomDialogManager;
import com.ssyc.student.R;
import com.ssyc.student.adapter.StGvWordPrepareAdapter;
import com.ssyc.student.bean.CloneWordPrepareInfo;
import com.ssyc.student.bean.CommitInfo;
import com.ssyc.student.bean.ResultInfo;
import com.ssyc.student.bean.StImgPrpareInfo;
import com.ssyc.student.util.TimeCount;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 学生端--词汇预习界面--听音频选择单词的界面
 * Created by Administrator on 2018/5/11 0011.
 */

public class StudentVocabularyPrepareSecondActivity extends BaseActivity implements View.OnClickListener {


    //获取LessonId的key
    public static final String LESSONID = "lessonid";

    //获取GradeId的key
    public static final String GRADEID = "gradeid";

    //LessonId
    private String lessonId;

    //GradeId
    private String gradeId;

    //所有条目数据的集合,需要将这个值传递个下个界面
    private List<CloneWordPrepareInfo.DataBean.QuestionListBean> data;

    //当前页面条目的位置
    private int currPos;

    //当前页面条目的对象
    private CloneWordPrepareInfo.DataBean.QuestionListBean info;

    //返回
    private ImageView ivBack;
    //进度条
    private ZzHorizontalProgressBar pb;
    //显示进度条的文本
    private TextView tvPb;
    //音频播放
    private ImageView ivPlay;
    //展示选项的列表
    private GridView gv;

    //数据集合
    private List<StImgPrpareInfo> stImgPrpareInfos;
    private StGvWordPrepareAdapter adapter;

    //通知Activity关闭的标识
    public static final int CLOSE = 0x150;

    //弹出是否提交的Dialog
    private Dialog dialog;

    //音频播放对象
    MediaPlayer player;

    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return null;
    }

    @Override
    protected int getContentLayout() {
        return R.layout.student_activity_vocabulary_prepare_two;
    }

    @Override
    protected void init() {

        showContent();

        //初始化视图
        initView();

        //模拟初始化数据
        initData();

        //设置进度条的数据
        initPbData();

        //设置适配器数据
        initGv();

    }


    /**
     * 初始化视图
     */
    public void initView() {
        ivBack = findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);
        pb = findViewById(R.id.pb);
        tvPb = findViewById(R.id.tv_pb);
        ivPlay = findViewById(R.id.iv_play);
        ivPlay.setOnClickListener(this);
        gv = findViewById(R.id.gv);
    }


    /**
     * 模拟初始数据
     */
    private void initData() {
        //获取传递过来的LessonId和gradeId
        lessonId = getIntent().getStringExtra(LESSONID);
        gradeId = getIntent().getStringExtra(GRADEID);

        //获取所有条目的数据
        data = GsonUtil.jsonToList(getIntent().getStringExtra("questioninfos"), CloneWordPrepareInfo.DataBean.QuestionListBean[].class);

        //获取当前位置
        currPos = getIntent().getIntExtra("currpos", -1);

        //得到当前页面条目的对象
        info = data.get(currPos);

        stImgPrpareInfos = new ArrayList<>();

        if (null != info && info.getJpglist() != null && info.getJpglist().size() != 0) {
            for (int i = 0; i < info.getJpglist().size(); i++) {
                StImgPrpareInfo imgPrpareInfo = new StImgPrpareInfo();
                imgPrpareInfo.isChoosed = false;
                imgPrpareInfo.url = info.getJpglist().get(i).getPicture();
                stImgPrpareInfos.add(imgPrpareInfo);
            }
        }

    }

    /**
     * 设置进度条的数据
     */
    private void initPbData() {
        //进度条的进度
        pb.setProgress((int) (MathUtil.deciMal((currPos + 1), data.size()) * 100));
        //显示进度的文字
        tvPb.setText((currPos + 1) + "/" + data.size());
    }

    /**
     * 设置列表的方法
     */
    private void initGv() {
        adapter = new StGvWordPrepareAdapter(info.getWordpic(), this, stImgPrpareInfos, R.layout.st_gv_item_word_prepare);
        gv.setAdapter(adapter);
        gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {
                //条目点击事件
                if (stImgPrpareInfos.get(pos).isChoosed) {
                    //证明已经选择过了,不能再次选择
                    UiUtils.Toast("已经展示答案,不能再次选择", false);
                    return;
                } else {

                    //根据当前条目的内容是否正确答案或者当前条目的位置是否是正确的位置,来进行播放录音文件
                    //正确则播放正确的录音,错误则播放错误的录音
                    //选择正确后根据当前位置如果是最后一个则跳出提交的弹框,否则跳转到StudentVocabularyPrepareThirdActivity界面
                    if (stImgPrpareInfos.get(pos).url.endsWith("/" + info.getWordpic())) {

                        //选项全部进行展示,并且不可再次点击
                        for (int i = 0; i < stImgPrpareInfos.size(); i++) {
                            if (stImgPrpareInfos.get(i).isChoosed != true) {
                                stImgPrpareInfos.get(i).isChoosed = true;
                            }
                        }

                        adapter.notifyDataSetChanged();

                        //设置列表不可再次交互
                        gv.setEnabled(false);

                        //如果当前条目的音频文件是以当前页面对象的Wordpic结尾,表示选择正确,播放正确录音
                        MediaPlayerManager.getInstance().playLocalFile(R.raw.rightmp3, new MediaPlayer.OnCompletionListener() {
                            @Override
                            public void onCompletion(MediaPlayer mediaPlayer) {


                            }
                        }, null);
                        if (currPos == data.size() - 1) {
                            //最后一个条目,弹出提交的对话框
                            showCommitPop();
                        } else {
                            //不是最后一个条目,跳转到StudentVocabularyPrepareThirdActivity界面
                            doNextQuestionAction();
                        }

                    } else {
                        //选择错误,播放错误录音
                        MediaPlayerManager.getInstance().playLocalFile(R.raw.errormp3, null, null);
                        stImgPrpareInfos.get(pos).isChoosed = true;
                        adapter.notifyDataSetChanged();
                    }


                }
            }
        });
    }


    /**
     * 进行下一题的操作,注意当前的索引值+1传递
     */
    private void doNextQuestionAction() {

        //不是最后一个条目,跳转到StudentVocabularyPrepareThirdActivity界面

        Intent intent = new Intent(StudentVocabularyPrepareSecondActivity.this, StudentVocabularyPrepareThirdActivity.class);

        //携带clone的数据集合过去
        intent.putExtra("questioninfos", GsonUtil.listToJson(data));

        //所有的单体点击进去都从给第一个开始学习
        intent.putExtra("currpos", currPos + 1);

        //携带
        intent.putExtra(StudentVocabularyPrepareSecondActivity.LESSONID, lessonId);
        intent.putExtra(StudentVocabularyPrepareSecondActivity.GRADEID, gradeId);

        startActivity(intent);
        finish();
    }


    /**
     * 提交的对话框
     */
    private void showCommitPop() {


        dialog = new Dialog(this, R.style.Common_Dialog_theme);

        View view = View.inflate(this, R.layout.st_pop_clean_cach, null);


        //关闭按钮
        ImageView ivClose = view.findViewById(R.id.lv_close);
        ivClose.setVisibility(View.GONE);
        //提示信息
        TextView tvMessage = view.findViewById(R.id.tv_message);
        tvMessage.setText("提交学习记录");
        Button btCommit = view.findViewById(R.id.bt_commit);
        btCommit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                doCommitAction();
            }
        });

        dialog.addContentView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));

        dialog.setCancelable(false);//不可取消

        dialog.show();


    }

    /**
     * 最后一题,进行提交按钮
     */
    private void doCommitAction() {

        CommitInfo commitInfo = new CommitInfo();

        //级别
        commitInfo.setGrade_id(gradeId);
        //课程编号
        commitInfo.setLesson_id(lessonId);
        //模块编号
        commitInfo.setModule_id("10");

        //题目总数量
        commitInfo.setAmount(data.size() + "");

        //正确题目数量
        commitInfo.setAmount_t(data.size() + "");

        //总分
        commitInfo.setScore("0");

        //得分
        commitInfo.setScore_t("0");

        //获取上传时间
        long useTime = TimeCount.newInstance().getTotalTime() + (System.currentTimeMillis() - TimeCount.newInstance().getLastTime());

        //转化为秒
        String seconds = useTime / 1000 + "";

        commitInfo.setSeconds(seconds);

        List<CommitInfo.SubjectBean> subjectBeans = new ArrayList<>();
        for (int i = 0; i < data.size(); i++) {
            CommitInfo.SubjectBean subjectBean = new CommitInfo.SubjectBean();

            //题目编号
            subjectBean.setQuestion_id(data.get(i).getTitle() + "");

            //题型编号
            subjectBean.setType_id(data.get(i).getTitletype() + "");

            //正确与否
            subjectBean.setResult("1");

            //填空内容
            subjectBean.setContent(data.get(i).getWordpic());

            //得分
            subjectBean.setScore("0");

            subjectBeans.add(subjectBean);
        }
        commitInfo.setSubject(subjectBeans);

        //转换成JSON字符串
        String postServerJson = GsonUtil.objectToJson(commitInfo);

        CustomDialogManager.show(this, "上传中...");

        String energy = StudentVocabularyPreviewActivity.ENERGY;
        if ("2".equals(AccountUtils.getRole(this))) {
            energy = "1";
        }
        Map<String, String> map = new HashMap<>();
        map.put("type", "24");
        map.put("acc", AccountUtils.getAccount(this));
        map.put("role", AccountUtils.getRole(this));
        map.put("studys", postServerJson);
        map.put("apptoken", AccountUtils.getToken(this));
        map.put("platform", "8");
        map.put("energy", energy);


        HttpUtils.post(HttpAdress.COMMITSCORE, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (null != dialog && dialog.isShowing()) {
                    dialog.dismiss();
                }
                UiUtils.Toast(BaseApplication.ERROR, false);
            }

            @Override
            public void onResponse(String response, int id) {
                if (null != dialog && dialog.isShowing()) {
                    dialog.dismiss();
                }
                ResultInfo info = null;
                if (!TextUtils.isEmpty(response)) {
                    try {
                        info = GsonUtil.jsonToBean(response, ResultInfo.class);
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.i("test", "数据解析异常");
                    }
                    if (info != null) {
                        if ("200".equals(info.state)) {
                            //上传成功
                            UiUtils.Toast("提交成功", false);
                            //通知StudentVocabularyPreviewActivity界面关闭
                            BusInfo busInfo = new BusInfo();
                            busInfo.setType(CLOSE);
                            EventBus.getDefault().post(busInfo);
                            //发送已经做完的更新
                            BusInfo stateInfo = new BusInfo();
                            stateInfo.setType(StudentChooseQuestionTypeActivity.UPDATAPAGESTATE);
                            EventBus.getDefault().post(stateInfo);
                            //关闭当前页面关闭
                            finish();
                        } else {
                            UiUtils.Toast("提交失败,错误码是:" + info.state, false);
                            Log.i("test", "错误码是:" + info.state);
                        }
                    }
                }
            }
        });
    }


    /**
     * 页面控件点击事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_back) {
            //返回
            finish();
        } else if (id == R.id.iv_play) {
            //播放音频并且执行帧动画
            playVoiceAndAnim();
        }
    }

    /**
     * 播放音频并且执行帧动画
     */
    private void playVoiceAndAnim() {
        //播放音频的按钮
        AnimationDrawable animationDrawable = (AnimationDrawable) ivPlay.getDrawable();
        animationDrawable.start();
        //播放录音
        MediaPlayerManager.getInstance().play(info.getSound(), new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        animationDrawable.stop();
                        //还原按钮需要展示的图片
                        ivPlay.setImageResource(R.drawable.st_voice_big_anim);
                    }
                });
            }
        }, new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        animationDrawable.stop();
                        //还原按钮需要展示的图片
                        ivPlay.setImageResource(R.drawable.st_voice_big_anim);
                    }
                });
                return false;
            }
        });
    }

    /**
     * 清空播放器对象
     */
    private void releasePlayer() {
        if (player != null) {
            try {
                player.stop();
                player.release();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                player = null;
            }
        }
    }

    /**
     * 切换页面时停止播放录音
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        MediaPlayerManager.getInstance().stop();
    }
}
